/**
 * 内部工具
 * enable: false
 */
module.exports = {
    sleep,
    sendNotify,
    request,
    obtainTokens
}

/**
 * 检索 bns_*_token
 * 获取环境变量配置的token
 * @returns {{name: string, token: string}[]}
 */
function getTokens() {
    return Object.entries(process.env)
        .filter(v => v[0].startsWith('bns_') && v[0].endsWith('_token'))
        .filter(v => {
            const result = _validToken(v[1])
            if (!result) {
                console.warn(`token:${v[0]}校验失败！`)
            }
            return result
        })
        .map(v => {
            return {
                name: v[0].replace('bns_', '')
                    .replace('_token', ''),
                token: v[1]
            }
        })
}

function obtainTokens() {
    const tokens = getTokens();
    if (!tokens.length) {
        throw '请检查token环境变量，必须包含【‘acctype’，‘openid’，‘access_token’，‘appid’】'
    }
    console.log(`获取到${tokens.length}个token：${tokens.map(v => v.name).join('，')}`)
    return tokens
}


/**
 * 校验token
 * 必须包含 【‘acctype’，‘openid’，‘access_token’，‘appid’
 * @param token {string}
 * @returns {boolean}
 * @private
 */
function _validToken(token) {
    const tokens = (token || '').split(';')
    if (!tokens.length) {
        return false
    }
    const result = {}
    tokens.forEach(token => {
        const [key, value] = token.trim().split('=');
        if (!key || !value) {
            return
        }
        result[key] = value
    })
    return (result['acctype'] &&
        result['openid'] &&
        result['access_token'] &&
        result['appid'])
}

/**
 * 发送bns请求
 * @param url 请求地址
 * @param params 请求参数
 * @param token 用户token
 * @returns {Promise<any>}
 */
function request({
                     url,
                     params,
                     token
                 }) {
    const formData = new FormData()
    for (let key in params) {
        formData.set(key, params[key])
    }

    return fetch(url, {
        method: 'post',
        body: formData,
        headers: {
            ContentType: 'application/x-www-form-urlencoded',
            cookie: token
        }
    }).then(res => res.json())
}

/**
 * 发送bark通知
 * @param tokenName 通过tokenName获取环境变量中配置的bark url
 * @param title 通知标题
 * @param body 通知内容
 */
function sendNotify({
                        tokenName,
                        title,
                        body
                    }) {

    const barkUrl = process.env[`bns_${tokenName}_bark`]
    if (!barkUrl) {
        return
    }
    const name = process.env[`bns_${tokenName}_name`]
    if (name) {
        body = `[${name}]${body}`
    }

    fetch(barkUrl, {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            title,
            body,
            icon: 'https://gitee.com/wangdadan/bns-ql/raw/main/sources/bns.png?a=1',
            group: 'bns',
            isArchive: '1'
        })
    }).then(res => res.json())
        .then(res => {
            if (res.code === 200) {
                console.log('发送成功')
            } else {
                console.error(`发送失败：${res.message}`)
            }
        })
}

/**
 * 暂停
 * @param time 毫秒树
 */
function sleep(time = 0) {
    if (!time) {
        return
    }
    const expireTime = Date.now() + time
    while (Date.now() <= expireTime) {

    }
}
